#include <stdlib.h>
#include "types.h"
#include "parallel_intersec.h"
#include "rasconnect/rasconnect.h"
#include "intersect.h"



typedef struct {
	long vacio; /* 127-> 96 */
	long vacio2; /* 95 -> 64 */
	char vacio3; /* 63 -> 48 */
	unsigned char valido; /* 47 -> 32 */
	unsigned long t; /* 31 ->  0 */
} t_rascBuffer_triangle;

void parallel_intersect(ray * ry) {
	object * cur;
	object temp;
	object *trn;
	t_rascBuffer_triangle *ptr;

	intersecta_triangulos(ry->scene->objgroup.parallelObjs, ry);

	/* launch triangles intersect meanwhile SW computes the rest */

	reset_intersection(ry); /* eliminate any existing intersections */

	/* do unbounded objects first, to help early-exit bounded object tests */
	temp.nextobj = ry->scene->objgroup.unboundedobj;
	cur = &temp;
	while ((cur = cur->nextobj) != NULL)
		cur->methods->intersect(cur, ry);

	/* do bounded objects last, taking advantage of early-exit opportunities */
	temp.nextobj = ry->scene->objgroup.boundedobj;
	cur = &temp;
	while ((cur = cur->nextobj) != NULL)
		cur->methods->intersect(cur, ry);


#ifdef RASC
	rcnc_wait(((ray *)ry)->scene->rasclib_id)
	// TODO: analiza estooo, t y su puta madre,
		trn = objs;
		for (i=0; i< ((ray *)ry)->scene->rascBtama; i++) {
			ptr = &((t_rascBuffer_triangle *)((ray *)ry)->scene->rascBuffer)[i];
			if (ptr->valido) {
				((ray*)ry)->add_intersection((ptr->t * 100000000), trn, ry);
			}
			trn = trn->nextobj;
		}
#endif
}

void intersecta_triangulos(const void * objs, void *ry) {
#ifdef RASC
	int i;


	/* triangles must be loaded in rasc already */

	rcnc_load_ray (((ray *)ry)->scene->rasclib_id, ry);
	rcnc_set_result_ptr(((ray *)ry)->scene->rasclib_id,
			((ray *)ry)->scene->rascBuffer,
			((ray *)ry)->scene->rascBtama);
	rcnc_go (((ray *)ry)->scene->rasclib_id);


#else
	const object *cur = objs;
	while (cur != NULL){
		cur->methods->intersect(cur, ry);
		cur = cur->nextobj;
	}
#endif
}
